<template>
  <!-- 课程展示 -->
  <div class="course-page">
    <div class="course-container">
      <el-row :gutter="20">
        <el-col v-for="course in courses" :key="course.cid" :xs="24" :sm="12" :md="8" :lg="6">
          <el-card class="course-card" shadow="hover">
            <!-- 课程图片 -->
            <img :src="course.imagePath || '/static/images/default-course.jpg'" class="course-image" @error="handleImageError" />

            <!-- 基础信息 -->
            <div class="course-info">
              <h3>{{ course.cname }}</h3>
              <p class="text1">{{ course.intro?.text1 }}</p>
            </div>

            <!-- 操作按钮 -->
            <div class="card-actions">
              <el-button type="primary" @click="handleEnroll(course)">立即选课</el-button>
              <el-link type="info" @click="toggleDetails(course)" class="details-link">
                {{ course.showDetails ? '收起详情' : '了解详情' }}
              </el-link>
            </div>

            <!-- 展开的详细信息 -->
            <div v-if="course.showDetails" class="course-details">
              <el-divider />
              <h4>{{ course.cname }}</h4>
              <p class="course-time">时间：{{ formatDate(course.stime) }} - {{ formatDate(course.etime) }}</p>
              <p>价格：¥{{ course.fullPrice }}</p>
              <p class="text2">{{ course.intro?.text2 }}</p>

              <!-- 教练信息 -->
              <div class="coach-info">
                <el-avatar :src="course.coachIntro?.avatarPath || '/static/images/default-avatar.jpg'" @click="toggleCoachIntro(course)" />
                <p class="coach-intro">
                  {{ course.coachIntro?.text1 }}
                  <span v-if="course.showCoachIntro" class="full-intro">{{ course.coachIntro?.text2 }}</span>
                </p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

// 课程数据
const courses = ref([]);

// 获取课程数据
const fetchCourses = async () => {
  try {
    const response = await axios.get('/api/courses');
    console.log('Courses Response:', response.data); // 打印返回数据

    const coursesData = response.data.map(course => ({
      ...course,
      showDetails: false,
      showCoachIntro: false,
      intro: { text1: '默认介绍1', text2: '默认介绍2' }, // 默认值
      imagePath: course.imagePath || '/static/images/default-course.jpg', // 确保有默认图片路径
      fullPrice: course.fullPrice // 确保字段名一致
    }));

    // 获取每个课程的详情信息
    for (const course of coursesData) {
      try {
        const introResponse = await axios.get(`/api/courses/${course.cid}/intro`);
        course.intro = introResponse.data || { text1: '默认介绍1', text2: '默认介绍2' };
      } catch (error) {
        course.intro = { text1: '默认介绍1', text2: '默认介绍2' };
      }

      try {
        const coachIntroResponse = await axios.get(`/api/employees/${course.eid}/intro`);
        course.coachIntro = coachIntroResponse.data || { text1: '默认教练介绍1', text2: '默认教练介绍2' };

        // 打印图片路径
        console.log('Course Image Path:', course.imagePath);
        console.log('Coach Avatar Path:', course.coachIntro?.avatarPath);
      } catch (error) {
        course.coachIntro = { text1: '默认教练介绍1', text2: '默认教练介绍2' };
      }
    }

    courses.value = coursesData;
  } catch (error) {
    ElMessage.error('获取课程数据失败');
  }
};

// 图片加载失败处理
const handleImageError = (e) => {
  e.target.src = '/static/images/default-course.jpg';
};

// 切换详情显示
const toggleDetails = (course) => {
  course.showDetails = !course.showDetails;
};

// 切换教练介绍
const toggleCoachIntro = (course) => {
  course.showCoachIntro = !course.showCoachIntro;
};

// 日期格式化
const formatDate = (datetime) => {
  return new Date(datetime).toLocaleString();
};

// 选课操作
const handleEnroll = async (course) => {
  try {
    const uid = localStorage.getItem('uid');
    if (!uid) {
      ElMessage.error('请先登录');
      return;
    }

    const hasCourse = await axios.get(`http://localhost:8080/alipay/order/hadCourse/${uid}/${course.cid}`)
        .then(res => res.data);

    if (hasCourse.data == '课程存在'){
      ElMessage.error('已选过此课程');
      return;
    }

    // 检查是否存在待支付订单
    const orderExists = await axios.get(
        `http://localhost:8080/alipay/order/exists/${uid}/${course.cid}`
    ).then(res => res.data);

    if (orderExists) {
      // 如果已有待支付订单，直接打开支付页面
      const existingOrderRes = await axios.get(
          `http://localhost:8080/alipay/order/select/${uid}/${course.cid}`
      );
      const existingOrder = existingOrderRes.data.data;

      await initiatePayment(existingOrder.oid, course, uid);
      return;
    }

    // 创建新订单
    const orderResponse = await axios.post('http://localhost:8080/v1/user/order/insert', {
      uid: uid,
      cid: course.cid,
      total: course.fullPrice,
      cname: course.cname,
      status: '取消支付'
    });

    if (orderResponse.data.state !== 2001 || !orderResponse.data.data) {
      throw new Error(orderResponse.data.message || '订单创建失败');
    }

    const oid = orderResponse.data.data;
    await initiatePayment(oid, course, uid);

  } catch (error) {
    ElMessage.error(error.response?.data?.message || error.message);
  }
};


// 独立的支付初始化函数
const initiatePayment = async (oid, course, uid) => {
  const paymentUrl = `http://localhost:8080/alipay/pay?orderNo=${oid}`;

  const payWindow = window.open(paymentUrl, '_blank', 'width=800,height=600');
  if (!payWindow) {
    throw new Error('请允许弹出窗口完成支付');
  }

  // 简化后的轮询逻辑（仅检查支付窗口是否关闭）
  const checkInterval = setInterval(() => {
    if (payWindow.closed) {
      clearInterval(checkInterval);
      // 支付窗口关闭后刷新课程列表（后端已完成选课操作）
      fetchCourses();
      ElMessage.success('支付流程已完成');
    }
  }, 2000);
};


// 组件挂载时获取数据
onMounted(() => {
  fetchCourses();
});
</script>

<style scoped>
.course-page {
  padding: 20px;
  background-color: #f5f7fa;
}

.course-container {
  max-width: 1200px;
  margin: 0 auto;
}

.course-card {
  margin-bottom: 20px;
  border-radius: 10px;
  transition: transform 0.3s ease;
}

.course-card:hover {
  transform: translateY(-5px);
}

.course-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 10px 10px 0 0;
}

.course-info {
  padding: 15px;
  text-align: center;
}

.course-info h3 {
  font-size: 18px;
  margin-bottom: 10px;
  color: #333;
}

.course-info .text1 {
  font-size: 14px;
  color: #666;
}

.card-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px 15px;
}

.details-link {
  font-size: 14px;
  color: #409EFF;
  cursor: pointer;
}

.details-link:hover {
  text-decoration: underline;
}

.course-details {
  padding: 15px;
}

.course-details h4 {
  font-size: 16px;
  margin-bottom: 10px;
  color: #333;
}

.course-details p {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.coach-info {
  display: flex;
  align-items: center;
  margin-top: 15px;
}

.coach-info .el-avatar {
  margin-right: 10px;
}

.coach-intro {
  font-size: 14px;
  color: #666;
}

.full-intro {
  display: block;
  margin-top: 5px;
  font-size: 12px;
  color: #999;
}
</style>
